import os

from database.mapper.stock_monitor import StockMonitorDto
from utils import doc_util, json_util, read_config, date_util
from service import data_service
from database.mapper import stock_monitor, stock_info as t_stock, monitor_strategy_config

user_path = os.path.join(read_config.data_path, 'common', 'users')
mark_path = os.path.join(read_config.data_path, 'webs', 'mark', 'users')
task_path = os.path.join(read_config.data_path, 'task', 'document', '突破均线')


# 更新标志
def del_flag():
    if os.path.exists(os.path.join(mark_path, 'user_up')):
        os.remove(os.path.join(mark_path, 'user_up'))


# 添加标志
def add_flag():
    doc_util.gen_new_doc(mark_path, 'user_up', [1])


# 更新标志
def update_flag():
    file_list = doc_util.get_file_names(mark_path)
    if len(file_list) == 0:
        return 0
    return 1


# web 页面添加用户
def add_users(fname):
    doc_util.gen_new_doc(mark_path, 'user_up', [1])
    new_fname = os.path.join(user_path, fname.filename)
    fname.save(new_fname)  # 保存文件到指定路径
    return 'success'


# 用户增加监控代码
def add_stock_code(usercode, stockcode):
    msg = {'code': '0000', 'msg': ''}
    s_info = t_stock.selectone(stockcode)
    smd = StockMonitorDto()
    smd.code = stockcode
    smd.name = s_info.get('name')
    smd.user_id = usercode
    smd.total_hand = 0
    smd.prompt_interval = 3
    smd.note = ''
    count = stock_monitor.insert_one(smd)
    if count == 0:
        msg['msg'] = '已存在'
    else:
        msg['msg'] = '添加完成'
    return msg


# 删除定时任务监控
def del_stock_code(usercode, stockcode):
    msg = {'code': '0000', 'msg': '删除完成'}
    count = stock_monitor.delete_monitor(usercode, stockcode)
    if count == 0:
        msg['msg'] = '不在监控中'
    return msg


# 删除持仓标志
def give_hold_stock_code(usercode, stockcode):
    msg = {'code': '0000', 'msg': ''}
    file_names = doc_util.get_file_names(user_path)
    s_dict = {}
    for file in file_names:
        if file == usercode:
            stock_list = doc_util.get_path_doc_info(os.path.join(user_path, file))
            for stock_info in stock_list:
                stock_info = json_util.info_to_json(stock_info)
                s_dict[stock_info['code']] = stock_info
    if stockcode in s_dict.keys():
        msg['msg'] = '删除持仓成功'
        s_info = s_dict[stockcode]
        s_info['hold'] = 0
        s_dict[stockcode] = s_info
        doc_util.gen_a_doc(user_path, usercode, s_dict)
        add_flag()  # 增加更新标志
    return msg


# 添加持仓标志
def hold_stock_code(usercode, stockcode):
    msg = {'code': '0000', 'msg': ''}
    file_names = doc_util.get_file_names(user_path)
    s_dict = {}
    for file in file_names:
        if file == usercode:
            stock_list = doc_util.get_path_doc_info(os.path.join(user_path, file))
            for stock_info in stock_list:
                stock_info = json_util.info_to_json(stock_info)
                s_dict[stock_info['code']] = stock_info
    if stockcode in s_dict.keys():
        msg['msg'] = '持仓成功'
        s_info = s_dict[stockcode]
        s_info['hold'] = 1
        s_dict[stockcode] = s_info
        doc_util.gen_a_doc(user_path, usercode, s_dict)
        add_flag()  # 增加更新标志
    else:
        add_stock_code(usercode, stockcode)  # 添加监控
        hold_stock_code(usercode, stockcode)
        msg['msg'] = '持仓成功'
    return msg


# 添加持仓标志
def stock_hold_update(usercode, stockcode, stockhold):
    msg = {'code': '0000', 'msg': ''}
    if stock_monitor.update_monitor_hold(usercode, stockcode, stockhold) == 1:
        msg['msg'] = '更改成功'
    else:
        msg['msg'] = '更改失败'
    return msg


# 添加持仓标志
def stock_note_update(usercode, stockcode, stocknotes: list):
    msg = {'code': '0000', 'msg': ''}
    if stock_monitor.update_monitor_note(usercode, stockcode, str(stocknotes)) == 1:
        msg['msg'] = '更改成功'
    else:
        msg['msg'] = '更改失败'
    return msg


# 获取用户所有的监控股票
def get_all_monitor(usercode: str) -> list:
    return sorted(stock_monitor.select_all(usercode), key=lambda x: x['total_hand'], reverse=True)


# 获取所有的监控代码
def get_all_stock():
    monitor_dict = doc_util.get_a_doc_dict(os.path.join(task_path, 'stock_virtual_hold'), 'code')
    s_dict = data_service.new_stock_all()
    for monitor in monitor_dict.keys():
        if monitor not in s_dict:
            data_service.stock(monitor)
        else:
            s_dict.pop(monitor)
    return {'监控中': monitor_dict, '未监控': s_dict}


# 删除监控中
def monitor_del(code):
    msg = {'code': '0000', 'msg': '删除成功'}
    monitor_dict = doc_util.get_a_doc_dict(os.path.join(task_path, 'stock_virtual_hold'), 'code')
    if code in monitor_dict.keys():
        monitor_dict.pop(code)
        doc_util.gen_a_doc(task_path, 'stock_virtual_hold', monitor_dict)
        add_flag()
    else:
        msg['msg'] = '已经删除'
    return msg


def monitor_add(code):
    msg = {'code': '0000', 'msg': '添加成功'}
    monitor_dict = doc_util.get_a_doc_dict(os.path.join(task_path, 'stock_virtual_hold'), 'code')
    if code not in monitor_dict.keys():
        monitor_dict[code] = data_service.stock(code)
        doc_util.gen_a_doc(task_path, 'stock_virtual_hold', monitor_dict)
        add_flag()
    else:
        msg['msg'] = '已经监控'
    return msg


# 更新用户监控配置
def strategy_conf_update(request, usercode):
    try:
        if 'strategyid' in request.form and request.form['strategyid'] != '0':
            monitor_strategy_config.update_status_by_id(request.form['strategyid'], request.form['status'])
        else:
            stockcode = request.form['stockcode']
            strategycode = request.form['strategycode']
            validdays = request.form['validdays']
            data_ext = {'code': stockcode}
            data_ext['strategy_code'] = strategycode
            data_ext['user_code'] = usercode
            data_ext['bs_flag'] = request.form['bs']
            data_ext['validdays'] = validdays
            data_ext['promptinfo'] = request.form['promptinfo']
            data_ext['valid_beg_date'] = date_util.get_date_str()
            data_ext['valid_end_date'] = date_util.add_day_str(date_util.get_date_str(), int(validdays))
            if strategycode[0:2] == '11':
                data_ext['pricetype'] = request.form['pricetype']
                data_ext['stockprice'] = request.form['stockprice']
                data_ext['type'] = 1
                if data_ext['stockprice'] == '0':
                    return '参数错误'
            if strategycode[0:2] == '12':
                data_ext['avetype'] = request.form['avetype']
                data_ext['avedays'] = request.form['avedays']
                data_ext['type'] = 2
                if request.form['avedays'] == '0':
                    return '参数错误'
            if strategycode[0:2] == '13':
                data_ext['iotype'] = request.form['iotype']
                data_ext['iodays'] = request.form['iodays']
                data_ext['type'] = 3
                if request.form['iodays'] == '0':
                    return '参数错误'
            if strategycode[0:2] == '14':
                data_ext['macdtype'] = request.form['macdtype']
                data_ext['macddays'] = request.form['macddays']
                data_ext['type'] = 4
                if request.form['macddays'] == '0':
                    return '参数错误'
            data_ext['status'] = 1
            data_ext['conf_info'] = str(data_ext)
            monitor_strategy_config.insert_one(data_ext)
    except:
        return '运行错误'
    return '设置成功'


if __name__ == '__main__':
    print('********start*******')
    update_flag()
    print('********end*******')
